package cn.wuxing.mediation.web.controller.common;

import cn.hutool.json.JSONUtil;
import cn.wuxing.mediation.businessplatform.mapper.business.CmEventApplicantMapper;
import cn.wuxing.mediation.businessplatform.mapper.business.CmNotDisputeEventMapper;
import cn.wuxing.mediation.common.core.domain.entity.CmEventApplicant;
import cn.wuxing.mediation.common.core.domain.entity.CmNotDisputeEvent;
import cn.wuxing.mediation.web.imports.domain.EventApplicantExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

public class EventApplicantListener implements ReadListener<EventApplicantExcel> {

    private final CmEventApplicantMapper eventApplicantMapper;
    private final CmNotDisputeEventMapper notDisputeEventMapper;
    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 100;
    private static final Logger log = LoggerFactory.getLogger(EventApplicantListener.class);
    /**
     * 缓存的数据
     */
    private List<EventApplicantExcel> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    public EventApplicantListener(CmEventApplicantMapper eventApplicantMapper, CmNotDisputeEventMapper notDisputeEventMapper) {
        this.eventApplicantMapper = eventApplicantMapper;
        this.notDisputeEventMapper = notDisputeEventMapper;
    }

    @Override
    public void invoke(EventApplicantExcel cmEventApplicant, AnalysisContext analysisContext) {
        log.info("【事件人员申请导入】- 解析到一条数据：{}", JSONUtil.toJsonStr(cmEventApplicant));
        cachedDataList.add(cmEventApplicant);

        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    private void saveData() {
        log.info("【事件人员申请导入】- {}条数据，开始存储数据库！", cachedDataList.size());
        if (cachedDataList.isEmpty()) {
            log.warn("【事件人员申请导入】- 解析的数据为空，忽略存储数据库操作。");
            return;
        }
        cachedDataList.forEach(excelData -> {
            try {
                CmEventApplicant entity = new CmEventApplicant();
                entity.setId(Long.valueOf(excelData.getSerialNumber()));
                LambdaQueryWrapper<CmNotDisputeEvent> eventQueryWrapper = Wrappers.lambdaQuery();
                eventQueryWrapper.eq(CmNotDisputeEvent::getEventCode, excelData.getEventCode());
                CmNotDisputeEvent notDisputeEvent = notDisputeEventMapper.selectOne(eventQueryWrapper);
                if (notDisputeEvent == null) {
                    return;
                }
                entity.setEventId(notDisputeEvent.getId());
                entity.setEventCategory(1);
                entity.setApplicantCategory(1);
                entity.setApplicantType("1");
                entity.setName(excelData.getName());
                entity.setIdCardType(excelData.getIdType());
                entity.setIdCard(excelData.getIdNumber());
                entity.setSex(excelData.getGender() == null || excelData.getGender().equals("男") ? "1" : "2");
                entity.setAge(excelData.getAge());
                entity.setNationality(excelData.getEthnicity());
                entity.setPhone(excelData.getContact());
                entity.setResidentialAddress(excelData.getResidentialAddress());
                entity.setCompanyName(excelData.getOrganizationName());
                entity.setCompanyAddress(excelData.getOrganizationAddress());
                entity.setUscc(excelData.getUnifiedSocialCreditCode());
                entity.setIsHaveProxyUser(excelData.getHasAgent() != null && excelData.getHasAgent().equals("是") ? 1 : 0);
                if (excelData.getHasAgent() != null &&excelData.getHasAgent().equals("是")) {
                    entity.setProxyUserName(excelData.getAgentName());
                    entity.setProxyUserPhone(excelData.getAgentContact());
                    entity.setProxyUserSex(excelData.getAgentGender().equals("男") ? "1" : "2");
                    entity.setProxyUserIdCardType(excelData.getAgentIdType());
                    entity.setProxyUserIdCard(excelData.getAgentIdNumber());
                    entity.setProxyUserResidentialAddress(excelData.getAgentResidentialAddress());
//                entity.setPowerOfAttorneyPath(excelData.getPowerOfAttorneyPath());
                }

                eventApplicantMapper.insert(entity);
            }catch (Exception ex){
                log.error("【事件人员申请导入】- 解析数据异常，忽略存储数据库操作。", ex);
            }
        });
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
        log.info("【事件人员申请导入】-所有数据解析完成");

    }
}
